package com.koron.sinoprobe.web.ledger.controller;

import cn.hutool.poi.excel.WorkbookUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.koron.bean.base.Response;
import com.koron.bean.system.org.OrgBean;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.bean.workflow.RedirectQuery;
import com.koron.bean.workflow.WorkflowController;
import com.koron.common.core.annocation.CasUser;
import com.koron.common.core.business.system.feign.SystemFeignService;
import com.koron.common.core.business.workflow.templates.WorkFlowHandler;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.sinoprobe.config.Constants;
import com.koron.sinoprobe.web.ledger.bean.entity.SpProject;
import com.koron.sinoprobe.web.ledger.bean.query.SpProjectQuery;
import com.koron.sinoprobe.web.ledger.bean.vo.ProjectOverviewStat;
import com.koron.sinoprobe.web.ledger.bean.vo.SpProjectVO;
import com.koron.sinoprobe.web.ledger.service.SpProjectService;
import com.koron.sinoprobe.web.plan.bean.entity.SpPlan;
import com.koron.sinoprobe.web.plan.excel.SpPlanPackageListener;
import com.koron.sinoprobe.web.plan.excel.SpPlanStringStringConvertor;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @author twcao
 * @title: SpProjectController
 * @projectName GDH_EAM_V2
 * @description: 专项台账
 * @date 2021/12/115:01
 */
@Slf4j
@RestController
@RequestMapping("/sp/project/")
@Api(tags = "专项台账")
public class SpProjectController implements WorkflowController {

    @Autowired
    private SpProjectService projectService;

    @Autowired
    private SystemFeignService systemFeignService;

    @Autowired
    private WorkFlowHandler workFlowHandler;

    @GetMapping("/selectOne")
    @ApiOperation("专项项目详情查询")
    @ApiImplicitParam(name = "projectId", value = "专项项目id", required = true)
    public Response<SpProjectVO> selectOne(@CasUser @ApiIgnore EamUser user, @RequestParam String projectId) {
        SpProjectVO detail = ADOConnection.runTask(user.getCurrDs(), projectService, "selectOne", SpProjectVO.class, projectId);
        //Assert.isTrue(!detail.getDeleteFlag(), "专项项目不存在");
        return Response.ok("查询成功", detail);
    }

    @GetMapping("/queryList")
    @ApiOperation("专项项目分页查询")
    public Response<PageInfo<SpProjectVO>> queryList(@CasUser @ApiIgnore EamUser user, SpProjectQuery query) {
        PageInfo<SpProjectVO> page = ADOConnection.runTask(user.getCurrDs(), projectService, "page", PageInfo.class, query);
        return Response.ok("查询成功", page);
    }

    @GetMapping("/getProjectDept")
    @ApiOperation("获取项目台账的所有部门")
    public Response<List<OrgBean>> getProjectDept(@CasUser @ApiIgnore EamUser user) {
        List<OrgBean> list = ADOConnection.runTask(user.getCurrDs(), projectService, "getProjectDept", List.class);
        return Response.ok("查询成功", list);
    }

    @GetMapping("/getProjectOverview")
    @ApiOperation("获取项目台账的项目概览统计")
    public Response<ProjectOverviewStat> getProjectOverview(@CasUser @ApiIgnore EamUser user, @RequestParam Integer year, @RequestParam String hostDeptId) {
        ProjectOverviewStat stat = ADOConnection.runTask(user.getCurrDs(), projectService, "getProjectOverview", ProjectOverviewStat.class, year, hostDeptId);
        return Response.ok("查询成功", stat);
    }

    @GetMapping("/getProjectProgress")
    @ApiOperation("获取项目台账的项目进度条统计")
    public Response<Map> getProjectProgress(@CasUser @ApiIgnore EamUser user, @RequestParam Integer year, @RequestParam String hostDeptId) {
        Map<String, List<String>> progress = ADOConnection.runTask(user.getCurrDs(), projectService, "getProjectProgress", Map.class, year, hostDeptId);
        return Response.ok("查询成功", progress);
    }

    @GetMapping("/getProjectRef")
    @ApiOperation("获取项目台账的项目关联对应专项工程数据的次数")
    public Response<Integer> getProjectRef(@CasUser @ApiIgnore EamUser user, @ApiParam("项目id") @RequestParam String projectId, @ApiParam("专项工程操作类型，字典：sp_project_action") @RequestParam String projectAction) {
        Integer amount = ADOConnection.runTask(user.getCurrDs(), projectService, "getProjectRef", Integer.class, projectId, projectAction);
        return Response.ok("查询成功", amount);
    }

    @PostMapping("save")
    @ApiOperation("保存项目")
    public Response<SpProjectVO> save(@CasUser @ApiIgnore EamUser user, @RequestBody SpProjectVO detail) {
        SpProjectVO result = ADOConnection.runTask(user.getCurrDs(), projectService, "saveOrUpdate", SpProjectVO.class, detail);
        return Response.ok("保存成功", result);
    }

    @SneakyThrows
    @ApiOperation(value = "下载模板")
    @GetMapping("template")
    public void template(HttpServletResponse response) {
        String path = "excel/sp_project.xlsx";
        ClassPathResource classPathResource = new ClassPathResource(path);
        Workbook book = WorkbookUtil.createBook(classPathResource.getInputStream());
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("专项项目", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        book.write(response.getOutputStream());
    }

    @SneakyThrows
    @ApiOperation(value = "导入")
    @PostMapping("import")
    public Response<String> importFile(@RequestParam("file") MultipartFile file) {
        SpPlanPackageListener spPlanPackageListener = new SpPlanPackageListener(projectService);
        SpPlanStringStringConvertor spPlanStringStringConvertor = new SpPlanStringStringConvertor();
        EasyExcel.read(file.getInputStream(), SpPlan.class, spPlanPackageListener)
                .registerConverter(spPlanStringStringConvertor)
                .sheet("专项项目").doRead();
        return spPlanPackageListener.getSheetResponse();
    }

    @DeleteMapping("delete")
    @ApiOperation(value = "删除")
    public Response<String> delete(@RequestParam String id) {
        ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), projectService, "deleteById", Boolean.class, id);
        return Response.ok("删除成功", id);
    }


    @PostMapping("update")
    @ApiOperation(value = "更新")
    public Response update(@RequestBody SpProject spProject) {
        ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), projectService, "update", Boolean.class, spProject);
        return Response.ok();
    }


    @Override
    public Response updateState(RedirectQuery redirectQuery) {
        log.info("工作流更新: {}", JSON.toJSONString(redirectQuery));
        // 撤回或者废弃
        String id = redirectQuery.getDataId();
        if (redirectQuery.getOperation() == 32 ) {
            // 修改为待审核
            SpProject spProject = new SpProject();
            spProject.setId(id);
            spProject.setStatus(Constants.ProjectStatus.WAIT_REVIEW);
            ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), projectService, "update", Boolean.class, spProject);
        }

        // 废弃
        if (redirectQuery.getOperation() == 16 ) {
            // 修改为待审核
            SpProject spProject = new SpProject();
            spProject.setId(id);
            spProject.setStatus(Constants.ProjectStatus.ABANDON);
            ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), projectService, "update", Boolean.class, spProject);

            // 删除工作流
            workFlowHandler.delete(redirectQuery.getDataId());
        }

        return Response.ok();
    }

    @Override
    public Response updateEnd(RedirectQuery redirectQuery) {
        String id = redirectQuery.getDataId();
        String status = Constants.ProjectStatus.END;
        SpProject spProject = new SpProject();
        spProject.setId(id);
        spProject.setStatus(status);
        return Response.ok(ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), projectService, "update", Boolean.class, spProject));
    }


}
